package com.xvyy.tingshu.user.strategy;

import com.xvyy.tingshu.common.execption.TsException;
import com.xvyy.tingshu.model.user.UserInfo;
import com.xvyy.tingshu.model.user.UserVipService;
import com.xvyy.tingshu.model.user.VipServiceConfig;
import com.xvyy.tingshu.user.mapper.UserInfoMapper;
import com.xvyy.tingshu.user.mapper.UserVipServiceMapper;
import com.xvyy.tingshu.user.mapper.VipServiceConfigMapper;
import com.xvyy.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;

/**
 * ClassName: ProcessTypePayRecordByVip
 * Package: com.xvyy.tingshu.user.strategy
 *
 * @Description: 处理vip类型的支付记录策略类
 * @Author: xvyy
 * @Create: 2025/2/13 - 16:08
 * @Version: v1.0
 */
@Component(value = "1003")
@Slf4j
public class ProcessTypePayRecordByVip implements ProcessDefaultPayRecord {

    @Autowired
    private UserVipServiceMapper userVipServiceMapper;
    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;


    @Override
    public void processPayRecord(UserPaidRecordVo userPaidRecordVo) {
        // user_vip_service表中插入数据，记录vip服务信息
        String orderNo = userPaidRecordVo.getOrderNo();
        // 1. 查询数据库中是否存在该订单号的vip服务记录
        UserVipService userVipService = userVipServiceMapper.selectOne(new LambdaQueryWrapper<UserVipService>().eq(UserVipService::getOrderNo, orderNo));
        if (userVipService != null) {
            throw new TsException(201, "该vip类型的订单已经处理过，请不要重复处理");
        }
        userVipService = new UserVipService();
        userVipService.setOrderNo(orderNo);
        userVipService.setUserId(userPaidRecordVo.getUserId());
        // 2. 根据订单号获取vip套餐信息
        VipServiceConfig vipServiceConfig = vipServiceConfigMapper.selectById(userPaidRecordVo.getItemIdList().get(0));
        if (vipServiceConfig == null) {
            throw new TsException(201, "根据订单号获取vip套餐信息失败");
        }

        Integer serviceMonth = vipServiceConfig.getServiceMonth();// 获取服务时长（月）
        // 3. 根据用户id获取用户信息
        UserInfo userInfo = userInfoMapper.selectById(userPaidRecordVo.getUserId());
        // 4. 根据用户信息获取vip身份和过期时间
        Calendar calendar = getCalendar(userInfo);
        // 5. 记录vip服务记录
        userVipService.setStartTime(new Date());// 设置开始时间
        calendar.add(Calendar.MONTH, serviceMonth);// 增加服务时长（月）
        userVipService.setExpireTime(calendar.getTime());// 设置过期时间
        int vipLogCount = userVipServiceMapper.insert(userVipService);
        log.info("保存订单号为{}的vip类型{}，数据记录到数据库影响行数为{}", orderNo, vipLogCount > 1 ? "成功" : "失败", vipLogCount);
        // 6. 更新用户信息
        userInfo.setIsVip(1);// 设置为vip
        userInfo.setVipExpireTime(userVipService.getExpireTime());// 设置vip过期时间
        int vipUpdateCount = userInfoMapper.updateById(userInfo);
        log.info("更新用户信息{}，数据记录到数据库影响行数为{}", vipUpdateCount > 1 ? "成功" : "失败", vipUpdateCount);
    }

    /**
     * 获取日期对象
     * @param userInfo
     * @return
     */
    private static @NotNull Calendar getCalendar(UserInfo userInfo) {
        // 1. 获取用户的vip身份
        Integer isVip = userInfo.getIsVip();
        // 2 获取vip过期时间
        Date vipExpireTime = userInfo.getVipExpireTime();
        // 3. 获取日期对象
        Calendar calendar = Calendar.getInstance();
        // 4. 判断用户是否已经是vip
        if (isVip == 0) {
            // 4.1 不是vip
            calendar.setTime(new Date());
        } else {
            // 4.2 是vip
            if (vipExpireTime.before(new Date())) {
                // 4.2.1 是vip 过期了
                calendar.setTime(new Date());
            } else {
                // 4.2.2 是vip 没过期
                calendar.setTime(vipExpireTime);
            }
        }
        return calendar;
    }

}
